var express = require('express');
var router = express.Router();
var multiparty = require('multiparty')
var util = require('util');
var fs = require('fs');
// 这个里面是要查询主页列表
var questionModel = require('../modules/questionModel')
/* GET home page. */
router.get('/', function(req, res, next) {
  // res.send('Hellow world')
  // 会主动到views里面去寻找index.ejs
  // 当loginbean3存入到session中的时候，它就成为全局的，任何时候都能调用到他首先要有req
  // console.log(req.session)
  loginbean = req.session.loginbean;
  questionModel.queList(req,res,loginbean);
  // console.log(loginbean,{ loginbean:loginbean})
  // res.render('index', { title:'Ejs2',loginbean:loginbean});
});
// 注销session
router.get('/logout',function(req,res){
	req.session.destroy(function(err){
		res.redirect('/')
	})
})
// 
router.post('/uploadImg',function(req,res){
  console.log('已选择图片并确定，返回图片路径，并上传成功')
  var form = new multiparty.Form(); 
  //设置编码 
  form.encoding = 'utf-8'; 
  //设置文件存储路径 
  form.uploadDir = "./uploadtemp/"; 
  //设置单文件大小限制 
  form.maxFilesSize = 2 * 1024 * 1024; 
  //form.maxFields = 1000;  设置所以文件的大小总和 
    
  form.parse(req, function(err, fields, files) { 
    var uploadurl='/images/upload/' 
    var file1 = files['filedata']; 
    var paraname = file1[0].fieldName;  //参数名filedata 
    var originalFilename = file1[0].originalFilename; //原始文件名 
    var tmpPath = file1[0].path;//uploadtemp\CO_1Ku61Qt44T-mYVWzdcIbX.png 临时文件存放目录
    var fileSize = file1[0].size; //文件大小 
        
    var timestamp=new Date().getTime(); //获取当前时间戳 
    uploadurl += timestamp+originalFilename 
    var newPath= './public'+uploadurl; 

    var fileReadStream = fs.createReadStream(tmpPath); 
    var fileWriteStream = fs.createWriteStream(newPath); 
    fileReadStream.pipe(fileWriteStream); //管道流 
    fileWriteStream.on('close',function(){ 
      fs.unlinkSync(tmpPath);    //删除临时文件夹中的图片 
      console.log('copy over');  
      //  /images/upload/1517663314194774830557233419632.png
      res.send('{"err":"","msg":"'+uploadurl+'"}')  
    }); 
  }); 
})

/* 对页面路径hssso h2222o  hyyuyo  这样的路径都是可以的 */
router.get('/h*o', function(req, res, next) {
  res.send('正则匹配页面')
  // res.render('index', { title: 'Express' });
});

module.exports = router;
